#pragma once
#include <iostream>
#include <unordered_map>
#include <fstream>
#include <sstream>
#include "article.h"

using namespace std;

class article_register
{
private:
	unordered_multimap<string, article> reg;
public:

	article_register()
	{
	}

	~article_register()
	{
	}

	void read_from_file(string filename)
	{
		try
		{
			string str, row;
			ifstream fin(filename);
			while (getline(fin, row))
			{
				istringstream iss(row);
				getline(iss, str, '=');
				if (str.compare("article") == 0)
				{
					article a;
					iss >> a;
					if (a.get_date() != "N/A")
						reg.emplace(a.get_date(), a);
				}
			}
			fin.close();
		}
		catch (exception e)
		{
			cout << e.what() << endl;
		}
	}

	void save_to_file(string filename)
	{
		try
		{
			ofstream fout(filename);
			for (auto &a : reg)
			{
				fout << "article=" << a.second << endl;
			}
			fout.close();
		}
		catch (exception e)
		{
			cout << e.what() << endl;
		}
	}

	void operator()()
	{
		bool run_menu = true;
		while (run_menu)
		{
			system("cls");
			cout << "1: Read from file" << endl;
			cout << "2: Add article" << endl;
			cout << "3: Remove article" << endl;
			cout << "4: Edit article" << endl;
			cout << "5: List articles" << endl;
			cout << "6: Save to file" << endl;
 			cout << endl << "else: exit" << endl;
			int i;
			cin >> i;
			cin.get();

			switch (i)
			{
			case 1: read_register(); break;
			case 2:	add_article(); break;
			case 3: remove_article(); break;
			case 4: edit_article(); break;
			case 5: list(); break;
			case 6: save_register(); break;
			default: run_menu = false;  break;
			}
		}
	}

	void read_register()
	{
		string str;
		getline(cin, str);
		read_from_file(str);
	}

	void add_article()
	{
		article a;
		a.read();
		reg.emplace(a.get_date(), a);
	}

	void remove_article()
	{
		string str;
		getline(cin, str);
		auto res = reg.equal_range(str);
		int i = 0;
		system("cls");
		for (auto it = res.first; it != res.second; it++)
		{
			cout << i++ << it->second << endl;
		}
		cin >> i;
		cin.get();
		auto it = res.first;
		for (int j = 0; j < i; j++)
			it++;
		reg.erase(it);
	}

	void edit_article()
	{
		string str;
		getline(cin, str);
		auto res = reg.equal_range(str);
		int i = 0;
		system("cls");
		for (auto it = res.first; it != res.second; it++)
		{
			cout << i++ << it->second << endl;
		}
		cin >> i;
		cin.get();
		auto it = res.first;
		for (int j = 0; j < i; j++)
			it++;
		article a = it->second;
		reg.erase(it);
		a.read();
		reg.emplace(a.get_date(), a);
	}

	void list()
	{
		for (auto &a : reg)
		{
			cout << a.second << endl;
		}
		cin.get();
	}

	void save_register()
	{
		string str;
		getline(cin, str);
		save_to_file(str);
	}
};